// internal/repositories/auth_repository.go
package repositories

import (
	"mygin/internal/models"

	"gorm.io/gorm"
)

type AuthRepository interface {
	//CheckUserActive(userID uint) (bool, error)
	FindByUsername(username string) (*models.User, error)
	FindByTel(tel string) (*models.User, error)
	CreateUser(user *models.User) (*models.User, error)
}

type authRepo struct {
	DB *gorm.DB
}

func NewAuthRepository(db *gorm.DB) AuthRepository {
	return &authRepo{DB: db}
}

// func (r *authRepo) CheckUserActive(userID uint) (bool, error) {
// 	var user models.User
// 	if err := r.DB.Select("active").First(&user, userID).Error; err != nil {
// 		return false, err
// 	}
// 	return user.Active, nil
// }

func (r *authRepo) FindByUsername(username string) (*models.User, error) {
	var user models.User
	if err := r.DB.Where("username = ?", username).First(&user).Error; err != nil {
		return nil, err
	}
	return &user, nil
}

func (r *authRepo) FindByTel(tel string) (*models.User, error) {
	var user models.User
	if err := r.DB.Where("tel = ?", tel).First(&user).Error; err != nil {
		return nil, err
	}
	return &user, nil
}

func (r *authRepo) CreateUser(user *models.User) (*models.User, error) {
	result := r.DB.Create(user)
	if result.Error != nil {
		return nil, result.Error
	}

	if result.RowsAffected == 0 {
		return nil, gorm.ErrRecordNotFound
	}

	return user, nil
}
